<template>
  <div class="model_box" v-if="isvidel" @click.self="closeModel">
    <!-- 添加提示框组件 -->
    <transition name="toast-fade">
      <div class="toast-message" v-if="showToast">
        <div class="toast-content">
          <span class="toast-icon">ℹ️</span>
          <span class="toast-text">{{ toastMessage }}</span>
        </div>
      </div>
    </transition>

    <!-- 使用 transition 包装二维码弹窗 -->
    <transition name="qr-fade" appear>
      <div class="qr-modal" v-if="showQRCode" @click.stop>
        <div class="qr-content">
          <AnimatedQrCode :href="shareUrl" />
          <div class="close-btn" @click.stop="closeQRCode">×</div>
        </div>
    </div>
    </transition>

    <div class="model_box_back" @click.stop="triggerSurprise">
      <!-- 内容区域 -->
      <div class="content-wrapper" @click.stop>
        <div class="item_box_header">
            <div class="img_name">物品图</div>
            <div class="img_time">获取物品时间</div>
            <div class="img_number">次(第)</div>
        </div>
        <div :class="{item_box:true,ash:index%2==0}" v-for="(item,index) in reward_list_zs" :key="index">
            <div class="w_item_img">
                <div class="item_img">
                    <img :src="item.img" alt="" srcset="">
                </div>
            </div>
            <div class="obtain_time">
                {{item.time}}
            </div>
            <div class="number">{{index+1}}</div>
        </div>
      </div>
      
      <!-- 底部区域 -->
      <div class="footer" @click.stop>
        <div class="action-buttons">
          <button @click="downloadContent" class="action-btn download" :disabled="isDownloading">
            <span class="icon">📥</span>
            <span class="text">
              {{ isDownloading ? '正在下载...' : '下载内容' }}
            </span>
            <div class="progress-bar" v-if="isDownloading">
              <div class="progress" :style="{ width: downloadProgress + '%' }"></div>
            </div>
          </button>
          <button @click.stop="shareContent" class="action-btn share">
            <span class="icon">🔗</span>
            <span class="text">生成分享码</span>
          </button>
        </div>
      </div>

      <!-- 背景区域用于触发惊喜功能 -->
      <div class="background-trigger" ></div>

      
    </div>
  </div>
</template>

<script setup>
import {defineProps, ref, watch, defineEmits} from 'vue';
import html2canvas from 'html2canvas';
import { useRouter } from 'vue-router';
import AnimatedQrCode from '@/components/AnimatedQrCode.vue';

const router = useRouter();

const props = defineProps({
  isvidel: {
    type: Boolean,
    required: true
  },
  reward_list_z: {
    type: Array,
    required: true
  }
});

const emit = defineEmits(['update:isvidel']);

// 关闭模态框
const closeModel = () => {
  emit('update:isvidel', false);
  showQRCode.value = false;
  chufa.value = 0;
};

// 状态声明
const showQRCode = ref(false);
const shareUrl = ref('');
const chufa = ref(0);
const reward_list_zs = ref([]);

// 添加下载状态和进度
const isDownloading = ref(false);
const downloadProgress = ref(0);

// 添加提示框状态
const showToast = ref(false);
const toastMessage = ref('');

// 监听 props 变化
watch(() => props.isvidel, (newVal) => {
    if (newVal) {
        fn_reward_list();
    }
});

// 触发惊喜功能
const triggerSurprise = () => {
    chufa.value++;
    let time_chufa;
    if(chufa.value == 1) {
        time_chufa = setTimeout(() => {
            if(time_chufa) {
                clearTimeout(time_chufa);
            }
            chufa.value = 0;
        }, 1500);
    } else if(chufa.value > 5) {
        if(time_chufa) {
            clearTimeout(time_chufa);
        }
        router.push({ path: '/surprise' });
    }
};

function fn_reward_list() {
    const storedData = localStorage.getItem('z_reward_list');
    if(storedData) {
        const lis = localStorage.getItem('z_reward_list_z');
        reward_list_zs.value = JSON.parse(lis) || [];
    } else {
        reward_list_zs.value = props.reward_list_z || [];
    }
}

// 显示提示的函数
function showToastMessage(message, duration = 3000) {
    toastMessage.value = message;
    showToast.value = true;
    setTimeout(() => {
        showToast.value = false;
    }, duration);
}

// 修改分享功能
function shareContent() {
  console.log(reward_list_zs.value)
    // 检查数据长度
    if (reward_list_zs.value.length > 20) {
        showToastMessage('数据太多了，该功能还没完善');
        return;
    }

    const storedData = localStorage.getItem('z_reward_list');
    let defaultCode = storedData != null ? 13 : 6;

    const shareData = reward_list_zs.value.map(item => {
        let imgCode;
        const imgPath = item.img.split('/')[2].split('.')[0];
        switch (imgPath) {
            case 'hongbao': imgCode = 1; break;
            case 'hongbao1': imgCode = 2; break;
            case 'icon-': imgCode = 3; break;
            case 'kaoxiang-mianbaoa': imgCode = 4; break;
            case 'latiao': imgCode = 5; break;
            case 'libao': imgCode = 6; break;
            case 'shupian_': imgCode = 7; break;
            case 'sucaizhuangshi': imgCode = 8; break;
            case 'tangguo': imgCode = 9; break;
            case 'tangmumao-': imgCode = 10; break;
            case 'wenduchuanganqi': imgCode = 11; break;
            case 'xie': imgCode = 12; break;
            case 'xinxi': imgCode = 13; break;
            default: imgCode = defaultCode;
        }
        
        return {
            d: item.id,
            t: item.time.split(' ')[0],
            imgCode
        };
    });

    // 检查编码后的数据长度
    const arrayString = JSON.stringify(shareData);
    if (arrayString.length > 2000) {
        showToastMessage('数据太多了，该功能还没完善');
        return;
    }

    const encodedArray = encodeURIComponent(arrayString);
    shareUrl.value = `http://danandgift.free3v.vip/share?array=${encodedArray}`;
    showQRCode.value = true;
}

// 关闭二维码
function closeQRCode() {
    showQRCode.value = false;
}

// 修改下载内容函数
async function downloadContent() {
    if (isDownloading.value) return;
    
    const targetElement = document.querySelector('.content-wrapper');
    if (!targetElement) {
        console.error('未找到要绘制的目标元素');
        return;
    }

    try {
        isDownloading.value = true;
        downloadProgress.value = 0;

        const progressInterval = setInterval(() => {
            if (downloadProgress.value < 90) {
                downloadProgress.value += Math.random() * 15;
            }
        }, 200);

        // 创建临时容器
        const tempContainer = document.createElement('div');
        tempContainer.style.cssText = `
            position: fixed;
            left: -9999px;
            width: ${targetElement.offsetWidth}px;
            background: white;
            padding: 20px;
            border-radius: 24px;
        `;
        document.body.appendChild(tempContainer);

        // 克隆内容到临时容器
        const contentClone = targetElement.cloneNode(true);

        // 应用样式到克隆元素
        contentClone.style.cssText = `
            background: white;
            padding: 20px;
            border-radius: 24px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        `;

        // 设置 header 样式
        const headerElements = contentClone.querySelectorAll('.item_box_header, .item_box_header > div');
        headerElements.forEach(header => {
            header.style.display = 'flex';
            header.style.justifyContent = 'center';
            header.style.alignItems = 'center';
            if (header.classList.contains('item_box_header')) {
                header.style.padding = '16px 0';
                header.style.marginBottom = '16px';
                header.style.borderBottom = '2px solid rgba(0, 0, 0, 0.08)';
                header.style.fontSize = '15px';
                header.style.fontWeight = '600';
                header.style.color = '#2c3e50';
            }
            if (header.classList.contains('img_name')) header.style.flex = '3';
            if (header.classList.contains('img_time')) header.style.flex = '7';
            if (header.classList.contains('img_number')) header.style.flex = '2';
        });

        // 设置 item_box 样式
        contentClone.querySelectorAll('.item_box').forEach(item => {
            item.style.cssText = `
                display: flex;
                height: 70px;
                margin: 12px 0;
                padding: 0 12px;
                border-radius: 12px;
                align-items: center;
                background: ${item.classList.contains('ash') ? 'rgba(0, 0, 0, 0.02)' : 'transparent'};
            `;
        });

        // 设置图片容器样式
        contentClone.querySelectorAll('.w_item_img').forEach(container => {
            container.style.cssText = `
                flex: 3;
                display: flex;
                justify-content: center;
                align-items: center;
            `;
        });

        // 设置图片样式
        contentClone.querySelectorAll('.item_img').forEach(imgContainer => {
            imgContainer.style.cssText = `
                width: 54px;
                height: 54px;
                border-radius: 12px;
                overflow: hidden;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            `;
            
            const img = imgContainer.querySelector('img');
            if (img) {
                img.style.cssText = `
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                `;
            }
        });

        // 设置时间和序号样式
        contentClone.querySelectorAll('.obtain_time').forEach(time => {
            time.style.cssText = `
                flex: 7;
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 14px;
                color: #4a5568;
                font-weight: 500;
            `;
        });

        contentClone.querySelectorAll('.number').forEach(num => {
            num.style.cssText = `
                flex: 2;
                display: flex;
                justify-content: center;
                align-items: center;
                font-weight: 600;
                color: #2d3748;
                font-size: 15px;
            `;
        });

        tempContainer.appendChild(contentClone);

        // 等待图片加载
        const images = contentClone.querySelectorAll('img');
        await Promise.all(Array.from(images).map(img => {
            if (img.complete) return Promise.resolve();
            return new Promise((resolve, reject) => {
                img.onload = resolve;
                img.onerror = reject;
            });
        }));

        const canvas = await html2canvas(contentClone, {
        scale: 2,
            useCORS: true,
            allowTaint: true,
            backgroundColor: '#ffffff',
            logging: true,
            onclone: (clonedDoc) => {
                const element = clonedDoc.querySelector('.content-wrapper');
                if (element) {
                    element.style.width = `${targetElement.offsetWidth}px`;
                }
            }
        });

        // 清理临时容器
        document.body.removeChild(tempContainer);

        clearInterval(progressInterval);
        downloadProgress.value = 100;

        // 创建下载链接
        const link = document.createElement('a');
        link.href = canvas.toDataURL('image/png', 1.0);
        link.download = 'content.png';
        link.click();

        // 重置状态
        setTimeout(() => {
            isDownloading.value = false;
            downloadProgress.value = 0;
        }, 500);

    } catch (err) {
        console.error('绘制或下载出错', err);
        isDownloading.value = false;
        downloadProgress.value = 0;
    }
}
</script>

<style lang="scss" scoped>
%center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.model_box {
  z-index: 999;
  position: fixed;
  inset: 0;
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(17, 23, 41, 0.85);
  backdrop-filter: blur(8px);
  animation: modalFadeIn 0.3s ease;

  .close-model-btn {
  position: absolute;
    top: 20px;
    right: 20px;
    width: 36px;
    height: 36px;
  border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
  cursor: pointer;
    font-size: 24px;
  transition: all 0.3s ease;
    backdrop-filter: blur(4px);
    z-index: 1001;
  
  &:hover {
      background: rgba(255, 255, 255, 0.3);
      transform: rotate(90deg);
  }
}

  .model_box_back {
    position: relative;
    width: 85%;
    max-width: 500px;
    height: auto;
    max-height: 75vh;
    margin: auto;
    background: linear-gradient(145deg, rgba(255, 255, 255, 0.95), rgba(255, 255, 255, 0.85));
    border-radius: 24px;
    padding: 24px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .background-trigger {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 0;
    }

    .content-wrapper,
    .footer {
      position: relative;
      z-index: 1;
    }

    .close-model-btn {
      position: absolute;
      top: 20px;
      right: 20px;
      z-index: 2;
    }

    .background-area {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 0;
    }

    .content-wrapper {
      flex: 1;
      overflow-y: auto;
      margin-bottom: 20px;
      
      &::-webkit-scrollbar {
        width: 0;
        height: 0;
        display: none;
      }
      scrollbar-width: none;
      -ms-overflow-style: none;
    }

    .footer {
      position: sticky;
      bottom: 0;
      left: 0;
      width: 100%;
      padding: 16px 0;
      background: inherit;
      border-top: 1px solid rgba(0, 0, 0, 0.05);
      
      &::before {
        content: '';
        position: absolute;
        bottom: 100%;
        left: 0;
        right: 0;
        height: 20px;
        background: linear-gradient(to top, rgba(255, 255, 255, 0.9), transparent);
        pointer-events: none;
      }
    }

    .item_box_header {
      display: flex;
      padding: 16px 0;
      margin-bottom: 16px;
      border-bottom: 2px solid rgba(0, 0, 0, 0.08);
      font-size: 15px;
      font-weight: 600;
      color: #2c3e50;
      letter-spacing: 0.5px;

      .img_name { flex: 3; @extend %center; }
      .img_time { flex: 7; @extend %center; }
      .img_number { flex: 2; @extend %center; }
    }

    .item_box {
      display: flex;
      height: 70px;
      margin: 12px 0;
      padding: 0 12px;
      border-radius: 12px;
      transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
      position: relative;

      &::before {
        content: '';
        position: absolute;
        inset: 0;
        background: linear-gradient(45deg, rgba(66, 153, 225, 0.1), rgba(99, 179, 237, 0.05));
        opacity: 0;
        transition: opacity 0.3s ease;
        border-radius: inherit;
      }

      &:hover {
        transform: translateX(8px) scale(1.02);
        z-index: 1;
        
        &::before {
          opacity: 1;
        }

        .item_img img {
          transform: scale(1.12);
        }
      }

      .w_item_img {
        flex: 3;
        @extend %center;
        
        .item_img {
          width: 54px;
          height: 54px;
          border-radius: 12px;
          overflow: hidden;
          box-shadow: 
            0 4px 12px rgba(0, 0, 0, 0.1),
            0 0 0 1px rgba(0, 0, 0, 0.05);
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.5s cubic-bezier(0.16, 1, 0.3, 1);
          }
        }
      }

      .obtain_time {
        flex: 7;
        @extend %center;
        font-size: 14px;
        color: #4a5568;
        font-weight: 500;
      }

      .number {
        flex: 2;
        @extend %center;
        font-weight: 600;
        color: #2d3748;
        font-size: 15px;
      }
    }

    &::-webkit-scrollbar {
      display: none;
    }

    &::-webkit-scrollbar-track {
      display: none;
    }

    &::-webkit-scrollbar-thumb {
      display: none;
    }
  }
}

// 添加交错动画
.item_box {
  &:nth-child(odd) {
    animation: slideInLeft 0.5s ease-out backwards;
  }
  &:nth-child(even) {
    animation: slideInRight 0.5s ease-out backwards;
  }
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.ash {
  background: rgba(0, 0, 0, 0.02);
}

.action-buttons {
  position: relative;
  display: flex;
  justify-content: center;
  gap: 16px;
  animation: slideUp 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

.action-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
  background: rgba(255, 255, 255, 0.9);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  position: relative;
  overflow: hidden;
  
  .icon {
    font-size: 16px;
  }

  .text {
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      left: 0;
      bottom: -2px;
      width: 100%;
      height: 2px;
      background: currentColor;
      transform: scaleX(0);
      transition: transform 0.3s ease;
      transform-origin: right;
    }
  }

  &:hover {
    transform: translateY(-2px);
    background: rgba(255, 255, 255, 1);
    
    .text::after {
      transform: scaleX(1);
      transform-origin: left;
    }
  }

  &:active {
    transform: translateY(0);
  }

  &.download {
    background: rgba(255, 255, 255, 0.9);
    color: #2c3e50;
    
    &:hover {
      background: rgba(255, 255, 255, 1);
    }
  }

  &.share {
    background: rgba(99, 102, 241, 0.2);
    color: white;
    
    &:hover {
      background: rgba(99, 102, 241, 0.3);
      
      .text::after {
        background: rgba(255, 255, 255, 0.5);
      }
    }
  }

  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
    transform: none !important;
  }

  .progress-bar {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 3px;
    background: rgba(0, 0, 0, 0.1);
    border-radius: 0 0 12px 12px;
    overflow: hidden;

    .progress {
      height: 100%;
      background: linear-gradient(
        90deg,
        rgba(99, 102, 241, 0.5),
        rgba(99, 102, 241, 0.8)
      );
      transition: width 0.3s ease;
      position: relative;
      
      &::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(
          90deg,
          transparent,
          rgba(255, 255, 255, 0.3),
          transparent
        );
        animation: shimmer 1.5s infinite;
      }
    }
  }
}

@keyframes shimmer {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(100%);
  }
}

// 动画关键帧
@keyframes modalFadeIn {
  from {
    opacity: 0;
    backdrop-filter: blur(0);
  }
  to {
    opacity: 1;
    backdrop-filter: blur(8px);
  }
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: scale(0.95) translateY(20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 二维码弹窗样式
.qr-modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;

  .qr-content {
    position: relative;
    padding: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    min-width: 300px;
    min-height: 300px;
    background: rgba(255, 255, 255, 0.05);
    border-radius: 15px;
    box-shadow: inset 0 0 15px rgba(255, 255, 255, 0.1);
    transform-origin: center;
    will-change: transform, opacity;
    
    &::before {
      content: '';
      position: absolute;
      inset: 0;
      border-radius: 15px;
      padding: 2px;
      background: linear-gradient(
        45deg,
        rgba(255, 255, 255, 0.1),
        rgba(255, 255, 255, 0.2)
      );
      mask: linear-gradient(#fff 0 0) content-box,
            linear-gradient(#fff 0 0);
      -webkit-mask-composite: xor;
      mask-composite: exclude;
      pointer-events: none;
    }
  }

  .close-btn {
    position: absolute;
    top: -15px;
    right: -15px;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: rgba(0, 0, 0, 0.8);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 18px;
    transition: all 0.3s ease;
    border: 2px solid rgba(255, 255, 255, 0.1);
    z-index: 2;

    &:hover {
      background: rgba(255, 0, 0, 0.8);
      transform: rotate(180deg) scale(1.1);
      border-color: rgba(255, 255, 255, 0.2);
    }
  }
}

// 优化二维码动画
.qr-fade-enter-active {
  animation: qrEnter 0.6s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.qr-fade-leave-active {
  animation: qrLeave 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes qrEnter {
  0% {
    opacity: 0;
    transform: translate(-50%, -45%) scale(0.8) rotate(-8deg);
    filter: blur(10px);
  }
  50% {
    opacity: 0.8;
    transform: translate(-50%, -52%) scale(1.1) rotate(3deg);
    filter: blur(0);
  }
  75% {
    transform: translate(-50%, -49%) scale(0.95) rotate(-1deg);
  }
  100% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1) rotate(0);
    filter: blur(0);
  }
}

@keyframes qrLeave {
  0% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1) rotate(0);
    filter: blur(0);
  }
  100% {
    opacity: 0;
    transform: translate(-50%, -45%) scale(0.85) rotate(6deg);
    filter: blur(8px);
  }
}

// 添加提示框样式
.toast-message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 2000;
  padding: 12px 24px;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 99px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(8px);

  .toast-content {
    display: flex;
    align-items: center;
    gap: 8px;
    color: white;
    font-size: 14px;
    
    .toast-icon {
      font-size: 16px;
    }

    .toast-text {
      font-weight: 500;
      letter-spacing: 0.5px;
    }
  }
}

// 提示框动画
.toast-fade-enter-active {
  animation: toastIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.toast-fade-leave-active {
  animation: toastOut 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes toastIn {
  from {
    opacity: 0;
    transform: translate(-50%, -20px);
  }
  to {
    opacity: 1;
    transform: translate(-50%, 0);
  }
}

@keyframes toastOut {
  from {
    opacity: 1;
    transform: translate(-50%, 0);
  }
  to {
    opacity: 0;
    transform: translate(-50%, -20px);
  }
}
</style>


